/***************************************************************************
 *   Copyright (C) 2008 by BogDan Vatra                                    *
 *   bogdan@licentia.eu                                                    *
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/

#include "thread_sql.h"

#include "blockingsocket.h"
#include <QSqlQuery>
#include <QVariant>
#include <QFile>
#include <QCryptographicHash>
#include <QSqlError>
#include <QSqlDatabase>
#include <QSqlResult>
//#include <QDebug>

#define BLOCKSIZE 0x400
#define TIMEOUT 10000l

extern QString dbName;
extern QString hostName;
extern QString userName;
extern uint connu;


ThreadSql::ThreadSql (int socketDescriptor, QObject *parent )
		: QThread ( parent ),m_socketDescriptor(socketDescriptor), m_sock(0)
{
    qDebug()<<"Running my thread";
    QSqlDatabase db=QSqlDatabase::addDatabase ("QPSQL",dbConnection);
    db.setDatabaseName("postgres");
    db.setHostName("127.0.0.1");
    db.setUserName("postgres");
    db.setPort(1307);
    if (!db.open())
    {
            qDebug()<<"can't open database"<<db.lastError().text();
            m_sock->disconnectFromHost();
    }
}


ThreadSql::~ThreadSql()
{
	QSqlDatabase::removeDatabase(dbConnection);
	delete m_sock;
}

QString toHex(QByteArray hex)
{
    QString val;
    for (int i=0;i<hex.size();i++)
    {
	QString h;
	h.sprintf("%02X",(unsigned char)hex[i]);
	val+=h;
    }
    return val;
}
void ThreadSql::run()
{



    m_sock = new BlockingSocket;
    if (!m_sock->setSocketDescriptor(m_socketDescriptor))
    {
        qDebug()<<"can't  setSoketDescriptor";
            return;
    }
    //m_sock->setTimeout(TIMEOUT);

    qDebug()<<"Running my thread";
    #define read_from_socket(WHAT) \
        if (sizeof(WHAT)!=m_sock->read((char*)&WHAT,sizeof(WHAT))) \
        {\
                qDebug()<<"different lenght";\
                m_sock->disconnectFromHost(); \
                if(QAbstractSocket::UnconnectedState!=m_sock->state()) \
                        m_sock->waitForDisconnected( TIMEOUT ); \
                return; \
        }

#define write_to_socket(MSG) \
        if (sizeof(MSG)!=m_sock->write((char*)&MSG,sizeof(MSG))) \
        { \
                qDebug()<<"different lengh in writet";\
                m_sock->disconnectFromHost(); \
                if(QAbstractSocket::UnconnectedState!=m_sock->state()) \
                        m_sock->waitForDisconnected( TIMEOUT ); \
                return;\
        } \


    char param[100];
    read_from_socket(param);
    qDebug()<<"readed from soket:"<<param;

    QSqlQuery  qry(param);
    if(!qry.exec())
    {
        qDebug()<<"fail to execute qry:"<<param;
        return ;
    }
    qry.first();
    qDebug()<<"query value"<<qry.value(0);
    write_to_socket(qry.value(0).toByteArray());

}
